let express = require('express')
let router = express.Router()

let mysqlHelper = require('../utils/mysqlHelper.js')
const utils = require('../utils/utils.js')

// 查询-tree maoyuan
router.get('/tree', async function(req, res, next) {
    let result = {}    
    try{
        rows = await mysqlHelper.query("select id,parentId,code,name,orderinlist as sort,remark from sys_dict order by orderinlist")
        myrows = rows.filter(row => row.parentId == '0') 
        myrows.forEach((dic, index, arr)=>{
            rows.children = rows.filter(row => row.parentId == dic.id) 
        })

        result.code=200
        result.data=myrows
        result.success = true
    }catch(err){
        result.code=400
        result.success = false
        result.message = err.message
    }
    res.json(result)
})

// 查询-某一项code
router.get('/listbycode', async function (req, res, next) {
    let result = {}
    try {

        let code = utils.getQueryValue(req.query.code)
        let sqlWhere = " where 1=1"
        sqlWhere += (code != '' ? " AND code='" + code + "'" : "")

        rows = await mysqlHelper.query("SELECT a.code,b.id,b.label as 'name',b.value as 'key',b.status as yx,b.dict_id as dic,b.orderinlist as sort \
                                        FROM sys_dict a INNER JOIN sys_dict_detail b on a.id=b.dict_id" + sqlWhere + " order by b.orderinlist ")
        result.code = 200
        result.data = {
            rows: rows,
        }
        result.success = true

    } catch (err) {
        result.code = 400
        result.success = false
        result.message = err.message
    }
    res.json(result)
})

// 查询-详细内容 maoyuan
router.get('/list', async function(req, res, next) {
    let result = {}    
    try{
        let pageSize = utils.getQueryValue(req.query.pageSize)
        let page = utils.getQueryValue(req.query.page)
        let code = utils.getQueryValue(req.query.code)
        let sqlWhere = " where 1=1"
        sqlWhere += ( code!='' ? " AND code='" + code + "'" : "")
        sqlLimit = "LIMIT "+(page-1)*pageSize+","+pageSize
        sqlLimit = ((sqlLimit.indexOf('NaN')||sqlLimit.indexOf("undefined"))?"":sqlLimit)
        total = (await mysqlHelper.query("SELECT count(1) as ct FROM sys_dict a INNER JOIN sys_dict_detail b on a.id=b.dict_id"+ sqlWhere))[0].ct
        rows = await mysqlHelper.query("SELECT b.id,b.label as 'name',b.value as 'key',b.status as yx,b.dict_id as dic,b.orderinlist as sort \
                                        FROM sys_dict a INNER JOIN sys_dict_detail b on a.id=b.dict_id" + sqlWhere +" order by b.orderinlist "+ sqlLimit)
        result.code=200
        result.data={
            'page': page,
            'pageSize':pageSize,
            'total': total,
            rows: rows,
        }
        result.success = true
    }catch(err){
        result.code=400
        result.success = false
        result.message = err.message
    }
    res.json(result)
})

// 字典键key修改新增  maoyuan
router.post('/key',async function(req, res, next) {
    let result = {}    
    try{
        let id = utils.getQueryValue(req.body.id)
        let sqlStr = ''
        let newid = ''
        if (id==''){  // 新增
            if ((await mysqlHelper.query("select count(1) as ct from sys_dict where code='" + req.body.code + "'"))[0].ct > 0) {
                throw new Error('该字典名称已被使用。')
            }
            sqlStr = "insert into sys_dict(code,name,parentId,remark,orderinlist,date) values('" + req.body.code + "','"+req.body.name+"',"+(req.body.parentId==''?0:req.body.parentId)+",'"+req.body.remark+"',"+req.body.sort+",now())"
            await mysqlHelper.query(sqlStr)
            newid = (await mysqlHelper.query("select id from sys_dict where code='"+req.body.code+"'"))[0].id
        }
        else{
            sqlStr = "update sys_dict set code='"+ req.body.code+"',name='"+ req.body.name +"',parentId="+req.body.parentId+",orderinlist="+ req.body.sort+",remark='"+ req.body.remark+"',date=now() where id="+ req.body.id
            await mysqlHelper.query(sqlStr)
            newid = req.body.id
        }
        result.code = 200       
        result.data = newid
        result.success = true
    }catch(err){
        result.code = 400
        result.success = false
        result.message = err.message
    }
    res.json(result)
})

// 字典键key删除  maoyuan
router.delete('/key',async function(req, res, next) {
    let result = {}    
    try {
        await mysqlHelper.query('delete from sys_dict_detail where dict_id=' + req.body.id)
        result.data = await mysqlHelper.query('delete from sys_dict where id=' + req.body.id)
        result.code = 200
        result.success = true
    } catch (err) {
        result.code = 400
        result.success = false
        result.message = err.message
    }
    res.json(result)
})


// 字典值value修改新增  maoyuan
router.post('/value',async function(req, res, next) {
    let result = {}    
    try{
        let id = utils.getQueryValue(req.body.id)
        let sqlStr =""
        if (id==''){  // 新增
            if ((await mysqlHelper.query("select count(1) as ct from sys_dict_detail where label='" + req.body.name + "' and value='" + req.body.key + "' and dict_id="+req.body.dic))[0].ct > 0) {
                throw new Error('该字典键值已被使用。')
            }
            sqlStr = "insert into sys_dict_detail(label,value,dict_id,status,orderinlist,createtime,date) values('" + req.body.name + "','"+req.body.key+"',"+req.body.dic+","+req.body.yx+","+req.body.sort+",now(),now())"
        }
        else{
            sqlStr = "update sys_dict_detail set label='"+ req.body.name+"',value='"+ req.body.key +"',dict_id="+req.body.dic+",orderinlist="+ req.body.sort+",status="+ req.body.yx+",date=now() where id="+ req.body.id
        }
        result.code = 200
        result.data = await mysqlHelper.query(sqlStr)
        result.success = true
    }catch(err){
        result.code = 400
        result.success = false
        result.message = err.message
    }
    res.json(result)
})

// 字典键value删除  maoyuan
router.delete('/value',async function(req, res, next) {
    let result = {}    
    try {
        result.data = await mysqlHelper.query("delete from sys_dict_detail where id in ("+ req.body.ids+")")
        result.code = 200
        result.success = true
    } catch (err) {
        result.code = 400
        result.success = false
        result.message = err.message
    }
    res.json(result)
})
module.exports = router